import Vue from 'vue'
import axios from 'axios'
import {Message, Loading} from 'element-ui'
import httpStatus from '../utils/httpStatus'
import store from '@/store'

axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest'
axios.defaults.withCredentials = true;
const _axios = axios.create({
    baseURL: '/api/',
    timeout: 5000
})
window.axios = Vue.prototype.axios = _axios
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest'

let loading = null

//请求拦截
_axios.interceptors.request.use(
    function (config) {
        if (config.url[0] == '/') {
            config.baseURL = ''
        }
        const token = window.localStorage.getItem("token");
        if (token) {
            config.headers["Authorization"] = `Bearer ${token}`;
        }
        //过滤发送get方法
        if (config.method !== "get") {
            loading = Loading.service({
                lock: true,
                text: '加载中...',
                spinner: 'el-icon-loading',
                background: 'rgba(255, 255, 255, 0.2)',
            })
        }

        return config
    },
    function (error) {
        //请求失败后，只能拦截除了get方法的其他所有方法
        loading.close()
        return Promise.reject(error)
    }
)

//响应拦截
_axios.interceptors.response.use(
    //请求成功
    function (response) {
        let {message} = response.data
        if (message) {
            Message({
                message,
                type: 'success'
            })
        }
        //过滤响应方法不是get
        if (response.config.method !== "get") {
            loading.close()
        }
        return response.data
    },
    //请求失败
    function (error) {
        let {
            status,
            data: {message, errors},
        } = error.response
        //过滤请求失败的get方法
        if (error.response.config.method !== "get") {
            loading.close()
        }
        switch (status) {
            case 422:
                store.commit('errors', errors)
                break
            case 403:
                Message({
                    message: message,
                    type: 'error'
                })
                break
            case 401:
                window.localStorage.removeItem('token')
                location.href = '/login'
                break
            default:
                Message({
                    message: message || httpStatus(status),
                    type: 'error'
                })
        }

        return Promise.reject(error)
    }
)
